<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button size="small" type="primary" @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="enableState"
            label="账户状态"
            sortable=""
          >
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            layout="prev, pager, next"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployee :showDialog.sync="showDialog" />
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeeAPI } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee";
import { formatDate } from "@/filters";
export default {
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      loading: false,
      showDialog: false,
    };
  },
  components: {
    AddEmployee,
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      this.loading = true;
      const { total, rows } = await getEmployeeListAPI(this.page);
      this.list = rows;
      this.page.total = total;
      this.loading = false;
    },
    changePage(newPage) {
      // 赋值最新的页码
      this.page.page = newPage;
      // 重新拉取数据
      this.getEmployeeList();
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    async delEmployee(id) {
      try {
        await this.$confirm("确认删除该员工吗");
        await delEmployeeAPI(id);
        this.$message.success("删除成功");
        this.getEmployeeList();
      } catch (error) {
        return Promise.reject(new Error(error));
      }
    },
    // 数据导出转换
    translate(inputData = [], mapRelation = {}) {
      // 拿到模板的key
      const header = Object.keys(mapRelation);
      // 遍历要导出的数据
      return inputData.map((item) => {
        const arr = [];
        // 循环模板key生成的数组
        header.forEach((zhKey) => {
          // 拿到模板中的每一项
          const enKey = mapRelation[zhKey];
          let value = item[enKey];
          // 如果拿到的是聘用形式，需要进行特殊处理
          // 找到枚举里id和value相等的值，相等的话就赋值给value，没有就未知
          if (enKey === "formOfEmployment") {
            const obj = EmployeeEnum.hireType.find((item) => item.id === value);
            value = obj ? obj.value : "未知";
          }
          // 如果拿到的是入职时间或转正时间，需要进行特殊处理
          // 调用formatDate过滤器
          if (enKey === "timeOfEntry" || enKey === "correctionTime") {
            value = formatDate(value);
          }
          arr.push(value);
        });
        return arr;
      });
    },
    // 数据导出
    exportData() {
      // 懒加载模块  => 只有点击按钮的时候才加载模块
      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 拉取模块
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 获取数据
        // 要想获取所有的数据，就要从第一页开始获取数据的总数
        const { rows } = await getEmployeeListAPI({
          page: 1,
          size: this.page.total,
        });
        // 转换数据
        const data = this.translate(rows, headers);
        const header = Object.keys(headers);
        // 执行导出
        excel.export_json_to_excel({
          filename: "人力资源表",
          header,
          data,
        });
      });
    },
  },
};
</script>
